<?php
/**
 * 商户管理
 */
namespace Merch\Controller;

use Common\Controller\AdminbaseController;

class AdminMerchController extends AdminbaseController {

    protected $merch_model;
    protected $category_model;

    function _initialize() {
        parent::_initialize();
        $this->merch_model = D("Merch/Merch");
        $this->category_model = D("Merch/MerchCategory");
        $this->merch_goods_model = D("Merch/MerchGoods");
    }

    // 后台商户管理列表
    public function index(){
        $where = array("merch_status"=>array('neq',-1));

        $cid = I('cid',0);
        if(!empty($cid)){
            $where['cid'] = $cid;
        }

        $fid = I('fid',0);
        if(!empty($fid)){
            $where['fid'] = $fid;
        }
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where['_string'] = "   `merch_name` LIKE '%$keyword%' OR `merch_description` LIKE '%$keyword%'   ";
        }

        $this->_lists($where);

        $cate_array = $this->category_model->where(['taxonomy'=>'merch'])->field(['cate_id'=>'cate_id','name'])->select();
        $html_option_categories = $this->generateSelectOptionHtml($cate_array,$cid,'全部');
        $this->assign('html_option_categories',$html_option_categories);
        // print_r($html_option_categories);

        $floor_array = $this->category_model->where(['taxonomy'=>'floor'])->field(['cate_id'=>'cate_id','name'])->select();
        $html_option_floors = $this->generateSelectOptionHtml($floor_array,$fid,'全部');
        $this->assign('html_option_floors',$html_option_floors);


        $this->display();
    }

    // 商户添加
    public function add(){

        $cate_array = $this->category_model->where(['taxonomy'=>'merch'])->field(['cate_id'=>'cate_id','name'])->select();
        $html_option_categories = $this->generateSelectOptionHtml($cate_array);
        $this->assign('html_option_categories',$html_option_categories);


        $floor_array = $this->category_model->where(['taxonomy'=>'floor'])->field(['cate_id'=>'cate_id','name'])->select();
        $html_option_floors = $this->generateSelectOptionHtml($floor_array);
        $this->assign('html_option_floors',$html_option_floors);

        $this->display();

    }

    // 商户添加提交
    public function add_post(){
        if (IS_POST) {
            if(empty($_POST['post']['cid'])){
                $this->error("请选择一个分类！");
            }
            if(empty($_POST['post']['fid'])){
                $this->error("请选择一个楼层！");
            }

            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['avatar'] = sp_asset_relative_url($_POST['smeta']['avatar']);

            $_POST['post']['update_time']=date("Y-m-d H:i:s",time());

            $merch=I("post.post");
            $merch['merch_type']="1";
            $merch['merch_pics']=json_encode($_POST['smeta']);
            $merch['merch_content']=htmlspecialchars_decode($merch['merch_content']);

            $result=$this->merch_model->add($merch);

            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }

        }
    }

    // 商户编辑
    public function edit(){
        $id=  I("get.id",0,'intval');
        $merchInfo = $this->merch_model->where("id=$id")->find();
        $this->assign("post",$merchInfo);
        $this->assign("smeta",json_decode($merchInfo['merch_pics'],true));
        // print_r($merchInfo['merch_pics']);

        $cate_array = $this->category_model->where(['taxonomy'=>'merch'])->field(['cate_id','name'])->select();
        $html_option_categories = $this->generateSelectOptionHtml($cate_array,$merchInfo['cid']);
        $this->assign('html_option_categories',$html_option_categories);

        $floor_array = $this->category_model->where(['taxonomy'=>'floor'])->field(['cate_id','name'])->select();
        $html_option_floors = $this->generateSelectOptionHtml($floor_array,$merchInfo['fid']);
        $this->assign('html_option_floors',$html_option_floors);

        $this->display();
    }

    /**
     * 商户编辑提交
     * @return [type] [description]
     */
    public function edit_post(){
        if (IS_POST) {
            if(empty($_POST['post']['cid'])){
                $this->error("请至少选择一个分类！");
            }
            if(empty($_POST['post']['fid'])){
                $this->error("请至少选择一个楼层！");
            }

            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }

            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['avatar'] = sp_asset_relative_url($_POST['smeta']['avatar']);

            $_POST['post']['update_time']=date("Y-m-d H:i:s",time());
            $merch=I("post.post");
            $merch['merch_type']="1";
            $merch['merch_pics']=json_encode($_POST['smeta']);
            $merch['merch_content']=htmlspecialchars_decode($merch['merch_content']);

            $result=$this->merch_model->save($merch);

            if ($result!==false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    /**
     * 商户排序
     * @return [type] [description]
     */
    public function listorders() {
        $merch_status = parent::_listorders($this->merch_relationships_model);
        if ($merch_status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    /**
     * 商户列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $cate_id=I('request.term',0,'intval');
        $where['merch_type']=array(array('eq',1),array('exp','IS NULL'),'OR');
        if(!empty($cate_id)){
            $where['b.cate_id']=$cate_id;
            $term=$this->category_model->where(array('cate_id'=>$cate_id))->find();
            $this->assign("term",$term);
        }

        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['create_time']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['create_time'])){
                $where['create_time']=array();
            }
            array_push($where['create_time'], array('ELT',$end_time));
        }

        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['merch_name']=array('like',"%$keyword%");
        }

        $this->merch_model
        ->alias("a")
        ->where($where);

        if(!empty($cate_id)){
            $this->merch_model->join("__MERCH_RELATIONSHIPS__ b ON a.id = b.merch_id");
        }

        $count=$this->merch_model->count();

        $page = $this->page($count, 20);

        $this->merch_model
        ->alias("a")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.create_time DESC");

        if(!empty($cate_id)){
            $this->merch_model->join("__MERCH_RELATIONSHIPS__ b ON a.id = b.merch_id");
        }

        $posts=$this->merch_model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);
    }



    /**
     * 获取商户分类树结构
     * @param  [type]  $id_name_array [description]
     * @param  integer $selected_id   [description]
     * @param  string  $default_name  [description]
     * @return [type]                 [description]
     */
    private function generateSelectOptionHtml($id_name_array,$selected_id = 0,$default_name='--请选择--'){
        $select_option_html = "<option value=\"0\"> {$default_name} </option>";
        foreach ($id_name_array as $item){
            $id = $item['cate_id'];
            $name = $item['name'];
            $selected_string = $id == $selected_id ? 'selected' : '';
            $select_option_html .= "<option value=\"{$id}\"  {$selected_string}>{$name}</option>";
        }
        return $select_option_html;
    }

    /**
     * [delete 商户删除]
     * @return [type] [description]
     */
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->merch_model->where(array('id'=>$id))->save(array('merch_status'=>"-1")) !==false) {
                $this->merch_goods_model->where(array('mid'=>$id))->save(array('goods_status'=>"-1"));
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');

            if ($this->merch_model->where(array('id'=>array('in',$ids)))->save(array('merch_status'=>"-1"))!==false) {
                $this->merch_goods_model->where(array('mid'=>array('in',$ids)))->save(array('goods_status'=>"-1"));
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

}